#include "evaluate.h"
#include "mainwindow.h"

EvaluationWidget::EvaluationWidget(QWidget *parent)
    : QWidget(parent)
    , submitBtn(nullptr)
    , viewResultsBtn(nullptr)
    , courseCombo(nullptr)
    , evaluationLayout(new QVBoxLayout)
{
    QString userType = UserSession::getInstance().getCurrentUserType();
    setupEvaluationGroups(userType);

    submitBtn = new QPushButton("提交", this);
    courseCombo = new QComboBox(this);

    if (userType == "supervisor") {
        viewResultsBtn = new QPushButton("查看最终评教情况表", this);
        connect(viewResultsBtn, &QPushButton::clicked, this, &EvaluationWidget::showEvaluationResults);
    }

    QHBoxLayout* comboLayout = new QHBoxLayout;
    comboLayout->addWidget(new QLabel("请选择课程：", this));
    comboLayout->addWidget(courseCombo);

    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addLayout(comboLayout);
    mainLayout->addLayout(evaluationLayout);
    mainLayout->addWidget(submitBtn);
    if (viewResultsBtn)
        mainLayout->addWidget(viewResultsBtn);

    setLayout(mainLayout);

    submitBtn->setEnabled(false);
    connect(submitBtn, &QPushButton::clicked, this, &EvaluationWidget::handleSubmit);
    connect(courseCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &EvaluationWidget::onCourseSelectionChanged);

    loadCourses();

}

void EvaluationWidget::setupEvaluationGroups(const QString &userType)
{
    QStringList questions;

    if (userType == "student") {
        questions << "您对这次课程的总体评价如何？"
                  << "课程所覆盖的内容量是否合理？"
                  << "教师是否将学习目标清晰地传达给学生？";
    } else if (userType == "teacher") {
        questions << "对课程内容的深度和广度评价"
                  << "教学资源的有效利用"
                  << "对自身教学目标的实现情况自评";
    } else if (userType == "supervisor") {
        questions << "课堂互动性评价"
                  << "专业素养评价"
                  << "教学组织能力评价";
    }

    // 清空旧组
    for (auto& criteria : evaluationCriterias)
    {
        evaluationLayout->removeWidget(static_cast<QGroupBox*>(criteria.group->parent()));
        delete criteria.group->parent();
    }
    evaluationCriterias.clear();

    // 创建新的评教组
    for (const QString& question : questions) {
        QButtonGroup *group = nullptr;
        QGroupBox *groupBox = createEvaluationGroup(question, group);
        evaluationCriterias.append({question, group});
        evaluationLayout->addWidget(groupBox);
    }
}

QGroupBox* EvaluationWidget::createEvaluationGroup(const QString& title, QButtonGroup*& group)
{
    QGroupBox *groupBox = new QGroupBox(title, this);
    QHBoxLayout *layout = new QHBoxLayout;
    group = new QButtonGroup(this);

    QRadioButton *radioButton_1 = new QRadioButton("一般", groupBox);
    QRadioButton *radioButton_2 = new QRadioButton("良好", groupBox);
    QRadioButton *radioButton_3 = new QRadioButton("满意", groupBox);

    group->addButton(radioButton_1, 1);
    group->addButton(radioButton_2, 2);
    group->addButton(radioButton_3, 3);

    layout->addWidget(radioButton_1);
    layout->addWidget(radioButton_2);
    layout->addWidget(radioButton_3);

    radioButton_1->setChecked(true);

    groupBox->setLayout(layout);
    return groupBox;
}

void EvaluationWidget::handleSubmit()
{
    SqlHelper &dbHelper = SqlHelper::getInstance();

    QString courseCode = courseCombo->currentData().toString();
    QVariantList course = dbHelper.queryCourseByCourseCode(courseCode);
    QString courseTeacher = course[5].toString();

    QString evaluationType = UserSession::getInstance().getCurrentUserType() + "_evaluation";

    if (UserSession::getInstance().getCurrentUserType() == "teacher") {
        if (courseTeacher != UserSession::getInstance().getCurrentUsername()) {
            evaluationType = "peer_evaluation";
        } else {
            evaluationType = "self_evaluation";
        }
    }

    double totalScore = 0.0;

    for (auto &criteria : evaluationCriterias) {
        totalScore += static_cast<double>(criteria.group->checkedId()); // 强制转换为浮点
    }

    double averageScore = totalScore / evaluationCriterias.size();

    if (dbHelper.updateEvaluation(courseCode, evaluationType, averageScore)) {
        QMessageBox::information(this, "Success", "评教成功！");
    } else {
        QMessageBox::warning(this, "Error", "评教失败！");
    }
}

void EvaluationWidget::loadCourses()
{
    SqlHelper &dbHelper = SqlHelper::getInstance();
    QList<QPair<QString, QString>> courses;

    if (UserSession::getInstance().getCurrentUserType() == "student")
    {
        courses = dbHelper.queryCoursesForUser(UserSession::getInstance().getCurrentUsername());
    }
    else
    {

        QList<QVariantList> queryResults = dbHelper.queryCourses();
        for (const QVariantList &row : queryResults) {
            if (row.size() >= 2) {
                QString courseName = row[1].toString();
                QString courseCode = row[0].toString();
                courses.append(qMakePair(courseName, courseCode));
            }
        }
    }

    for (const auto &course : courses) {
        courseCombo->addItem(course.first, course.second); // course.first 是名称，course.second 是课程代号
    }
    if (courseCombo->count() > 0) {
        submitBtn->setEnabled(true); // 如果有课程，则允许评分和提交
    }
}

void EvaluationWidget::onCourseSelectionChanged()
{
    qDebug() << "Selected course:" << courseCombo->currentText();

    SqlHelper &dbHelper = SqlHelper::getInstance();

    QString courseCode = courseCombo->currentData().toString();
    QVariantList course = dbHelper.queryCourseByCourseCode(courseCode);
    QString courseTeacher = course[5].toString();

    QString userType = UserSession::getInstance().getCurrentUserType();
    QString evaluationType;

    if (userType == "teacher") {
        evaluationType = (courseTeacher == UserSession::getInstance().getCurrentUsername()) ?
                "教师自评" : "同行评价";
    } else if (userType == "student") {
        evaluationType = "学生评价";
    } else {
        evaluationType = "督导评价";
    }

    for (auto &criteria : evaluationCriterias) {
        // 设置新的标题
        // 安全检查和正确传递父类指针
        if (QGroupBox *groupBox = qobject_cast<QGroupBox*>(criteria.group->parent())) {
//            QString newTitle = criteria.title + " - " + evaluationType;
//            groupBox->setTitle(newTitle);

        }

        MainWindow::ts->setWindowTitle(evaluationType);

        // 设置默认选中的选项
        criteria.group->button(1)->setChecked(true);
    }
    qDebug() << "6";
}

void EvaluationWidget::showEvaluationResults()
{
    SqlHelper &dbHelper = SqlHelper::getInstance();

    // 获取所有教师评教记录
    QList<QVariantList> teacherList = dbHelper.queryTeachers();
    QMap<QString, double> weights = dbHelper.queryEvaluationWeights();

    // 计算并展示评教情况
    QWidget *resultsWidget = new QWidget;
    QVBoxLayout *layout = new QVBoxLayout(resultsWidget);
    QTableWidget *tableWidget = new QTableWidget(teacherList.size(), 4, resultsWidget);

    tableWidget->setHorizontalHeaderLabels(QStringList() << "工号" << "教师姓名" << "学院" << "最终加权分");

    int row = 0;
    for (const auto &teacher : teacherList) {
        QString teacherName = teacher[1].toString();

        // 计算加权评分
        QList<QVariantList> evaluationRecords = dbHelper.queryEvaluationsForTeacher(teacherName);

        double weightedScoreSum = 0.0;
        int count = 0;

        for (const auto &eval : evaluationRecords) {

            double selfEval = eval[0].toDouble();
            double studentEval = eval[1].toDouble();
            double supervisorEval = eval[2].toDouble();
            double peerEval = eval[3].toDouble();

            double weightedScore = (selfEval * weights.value("self", 0.0) +
                                    studentEval * weights.value("student", 0.0) +
                                    supervisorEval * weights.value("supervisor", 0.0) +
                                    peerEval * weights.value("peer", 0.0));

            weightedScoreSum += weightedScore;
            count++;
        }

        double finalWeightedScore = count > 0 ? weightedScoreSum / static_cast<double>(count) : 0.0;

        tableWidget->setItem(row, 0, new QTableWidgetItem(teacher[0].toString())); // 工号
        tableWidget->setItem(row, 1, new QTableWidgetItem(teacherName));           // 教师姓名
        tableWidget->setItem(row, 2, new QTableWidgetItem(teacher[2].toString())); // 学院
        tableWidget->setItem(row, 3, new QTableWidgetItem(QString::number(finalWeightedScore, 'f', 2))); // 最终加权分

        row++;
    }

    tableWidget->resizeColumnsToContents(); // 根据内容自动调整列宽

    layout->addWidget(tableWidget);
    resultsWidget->setLayout(layout);
    resultsWidget->resize(800, 600);

    resultsWidget->show();
}
